<template>
  <!-- 外层容器 -->
  <div class="dong-pager" :class="{ [`dong-pager--${type}`]: type, [`dong-pager--${size}`]: size }">
    <!-- 首页 -->
    <a :class="currentPage === 1 ? 'disabled' : ''" @click.prevent="pageClick(1)">首页</a>
    <!-- 上一页 -->
    <a :class="currentPage === 1 ? 'disabled' : ''" :disabled="currentPage === 1" @click.prevent="prevClick">
      <Dong-Icon icon="angles-left" />
    </a>
    <!-- 根据pager渲染中间页 -->
    <a v-if="total > pageCount && currentPage > 5" @click.prevent="pageClick(1)">1</a>
    <a v-if="total > pageCount && currentPage > 5" @click.prevent="preEllipsisClick">
      <Dong-Icon icon="ellipsis" size="sm" />
    </a>
    <a v-for="page in pages" :key="page" :class="currentPage === page ? 'active' : ''"
      @click.prevent="pageClick(page)">{{
        page }}</a>
    <a v-if="total > pageCount && currentPage < total - 4" @click.prevent="nextEllipsisClick">
      <Dong-Icon icon="ellipsis" size="sm" />
    </a>
    <a v-if="total > pageCount && currentPage < total - 4" @click.prevent="pageClick(total)">
      {{ total }}
    </a>
    <a :class="currentPage === total ? 'disabled' : ''" :disabled="currentPage === total" @click.prevent="nextClick">
      <Dong-Icon icon="angles-right" /> </a>
    <a :class="currentPage === total ? 'disabled' : ''" @click.prevent="pageClick(total)">尾页</a>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import propObj from './props.js'
const props = defineProps(propObj)
defineOptions({ name: 'DongPager' })
const pages = computed(() => {
  // 该数组用于存放要渲染的页码
  const renderPage = []
  // 接下来就需要根据情况来进行判断了
  // 可以全部渲染的情况
  if (props.total <= props.pageCount) {
    for (let i = 1; i <= props.pageCount; i++) {
      renderPage.push(i)
    }
  } else {
    // 进入 else 说明总页码数是大于可渲染页面数，无法全部渲染，只能渲染一部分
    // 这里又分为三种情况
    // 当前页比较靠前：[1] 2 3 4 5 ... 20
    // 当前页比较靠中间：1 ... 5 6 [7] 8 9 ... 20
    // 当前页比较靠后：1 ... 16 17 18 19 [20]
    if (props.currentPage <= 5) {
      // 比较靠前
      for (let i = 1; i <= 5; i++) {
        renderPage.push(i)
      }
    } else if (props.currentPage >= props.total - 4) {
      // 比较靠后
      for (let i = props.total - 4; i <= props.total; i++) {
        renderPage.push(i)
      }
    } else {
      // 比较靠中间
      for (let i = props.currentPage - 2; i <= props.currentPage + 2; i++) {
        renderPage.push(i)
      }
    }
  }
  return renderPage
})
const emit = defineEmits(['current-change'])
function pageClick(page) {
  emit('current-change', page)
}
const prevClick = () => {
  if (props.currentPage === 1) return
  emit('current-change', props.currentPage - 1)
}

const nextClick = () => {
  if (props.currentPage === props.total) return
  emit('current-change', props.currentPage + 1)
}

const preEllipsisClick = () => {
  emit('current-change', props.currentPage - 5)
}
const nextEllipsisClick = () => {
  emit('current-change', props.currentPage + 5)
}
</script>

<style lang=" scss" scoped></style>
